<?php

namespace app\index\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;

class Calendar extends Model
{
    protected $table = 'user_caravan_calendar';

    const CALENDAR_IS_SHARE = 1;//分享
    const CALENDAR_IS_RENT = 2;//出租

    use TraitModel;
    /**
     * [test2 关联]
     * @return [type] [description]
     */
    // public function test2()
    // {
    //     return $this->belongsTo('Filters','caravan_id');
    // }
    /**
     * 初始化房车日历
     * @param  [type]  $caravan_id [description]
     * @param  integer $y          初始化年数
     * @return [type]              [description]
     */
    public function initCaravanCarlendar($caravan_id, $y = 1)
    {
        $caravan_info = model('CaravanInfos')->getCaravanInfo(self::getLoginUserInfo('id'));
        $diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::now());
        
        if ($caravan_datetimes = $this->where('caravan_id', $caravan_id)->order('datetimes', 'desc')->value('datetimes')) {
            $diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::createFromFormat('Y-n-j', $caravan_datetimes));
        }
        if ($diffday > 1) {
            $this->startTrans();
            try {
                for ($i=0; $i < $diffday; $i++) { 
                   $datetimes = Carbon::now()->addDay($i)->toDateString();
                   $is_holidy = model('Holidays')->holiday($datetimes);
                   $this->create(['caravan_id' => $caravan_id, 'camps_id' => $caravan_info->camp->id, 'is_holiday' => $is_holidy->is_holiday, 'datetimes' => $datetimes]);
                }
                $this->commit();

            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
        }
        return true;
    }
    public function setWhere($query = [])
    {
        $start_date = $query['start_date'];
        $end_date = isset($query['end_date']) ? $query['end_date'] : '';
        

        if (!is_array($start_date)) {
            if (strpos($start_date, ',')) {
                $start_date = explode(',', $start_date);
            }else{
                $end_date = $end_date ? : $start_date;  
            }
        }
        unset($query['start_date'], $query['end_date']);

        if (is_array($start_date)) {
            $this->where('datetimes', 'in', $start_date);
        }else{
            $this->where('datetimes', 'between', [$start_date, $end_date]);
        }

        $this->where($query);

        return $this;
    }
    /**
     * 设置会员房车状态日
     * @param [type] $caravan_id [description]
     * @param [type] $userType   [description]
     * @param [type] $status     [description]
     * @param [type] $start_date [description]
     * @param [type] $end_date   [description]
     */
    private function setUserCaravanCarlendar($caravan_id, $update_info)
    {
    	$this->startTrans();
    	try {
    		$this->update($update_info);
    		$this->refreshCaravanStatuDateLine($caravan_id);
    		$this->commit();
    	} catch (Exception $e) {
    		$this->rollback();
    		return false;
    	}
        return true;    	
    }
    /**
     * 设置用户房车分享时间段
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function setUserCaravanCarlendarIsShare($caravan_id, $start_date, $end_date = null)
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['shares' => 1]);
    } 
    /**
     * 分享获得积分
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function getIntergrtates($caravan_id, $start_date, $end_date = '')
    {
        $intergrate = 0;
        //获取营地房车基数
        //$base = 500;
        $user_id = session('user.id');
        $camp_id = model('Users')->where('id',$user_id)->value('camp_id');
        $travel_money_base = model('Camps')->where('id',$camp_id)->value('travel_money_base');

        if($days = $this->setWhere(['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0, 'shares' => 0])->select()){
            foreach ($days as $key => $day) {
                //积分
                $holiday_coefficient = $this->getCoefficient($day->datetimes);//假日系数
                $intergrate += $holiday_coefficient * $travel_money_base;
            }
        }
        return $intergrate;

    }
    /**
     * 取消分享减少积分
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function reduceIntergrtates($caravan_id, $start_date, $end_date = '')
    {
        $intergrate = 0;
        //获取营地房车基数
        //$base = 500;
        $user_id = session('user.id');
        $camp_id = model('Users')->where('id',$user_id)->value('camp_id');
        $travel_money_base = model('Camps')->where('id',$camp_id)->value('travel_money_base');

        if($days = $this->setWhere(['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0, 'shares' => 1])->select()){
            foreach ($days as $key => $day) {
                //积分
                $holiday_coefficient = $this->getCoefficient($day->datetimes);//假日系数
                $intergrate += $holiday_coefficient * $travel_money_base;
            }
        }
        return $intergrate;

    }

    /**
     * 用户分享房车时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function share($caravan_id, $start_date, $end_date = '')
    {
        $remark = '房车分享';
        $this->startTrans();
        try {
            model('Intergrates')->addIntergrates($this->getIntergrtates($caravan_id, $start_date, $end_date),$user_id = null, ['remark' => $remark]);
            $this->setUserCaravanCarlendarIsShare($caravan_id, $start_date, $end_date);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }

    /**
     * 取消用户分享房车时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function cancelCaravanShare($caravan_id, $start_date, $end_date = '')
    {
        $remark = '取消分享';
        $this->startTrans();
        try {
            model('Intergrates')->reduceIntergrates($this->reduceIntergrtates($caravan_id, $start_date, $end_date), $user_id = null, ['remark' =>$remark]);
            $this->cancelShare($caravan_id, $start_date, $end_date);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }

    /**
     * 取消分享
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function cancelShare($caravan_id, $start_date, $end_date = '')
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0, 'shares' => 1];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['shares' => 0]);
    }

    /**
     * 用户出租房车时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function rent($caravan_id, $start_date, $end_date = '', $single_day_price)
    {
        $this->startTrans();
        try {
            $this->setUserCaravanCarlendarIsRent($caravan_id, $start_date, $end_date, $single_day_price);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }
    /**
     * 设置用户房车心愿状态
     * @param [type] $caravan_id [description]
     * @param [type] $userType   [description]
     * @param [type] $start_date [description]
     * @param string $end_date   [description]
     */
    public function setUserCaravanCarlendarIsWish($caravan_id, $start_date, $end_date = '')
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'orders' => 0];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['wishs' => 1]);
    }
    /**
     * 解除用户房车心愿状态
     * @param [type] $caravan_id [description]
     * @param [type] $start_date [description]
     * @param string $end_date   [description]
     */
    public function setUserCaravanCarlendarIsUnWish($caravan_id, $start_date, $end_date = '')
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'orders' => 0];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['wishs' => 0]);
    }

    /**
     * 设置用户房车出租时间段
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function setUserCaravanCarlendarIsRent($caravan_id, $start_date, $end_date = '', $single_day_price)
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['rents' => 1, 'single_day_price' =>$single_day_price]);
    }

    /**
     * 取消出租
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function cancelCaravanRent($caravan_id, $start_date, $end_date = '', $single_day_price)
    {
        $querys = ['start_date' => $start_date, 'end_date' => $end_date, 'caravan_id' => $caravan_id, 'wishs' => 0, 'orders' => 0, 'rents' => 1];
        return $this->setWhere($querys)->setUserCaravanCarlendar($caravan_id, ['rents' => 0, 'single_day_price' =>$single_day_price]);
    }

    /**
     * 改变用户房车分享时间段为出租状态
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function changeUserCaravanCarlendarIsrent($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['rents' => 1]);
    }
    /**
     * 刷新房车状态时间段
     * @param  [type] $caravan_id [description]
     * @return [type]             [description]
     */
    protected function refreshCaravanStatuDateLine($caravan_id)
    {
    	model('CarCalendar')->where('caravan_id', $caravan_id)->delete();

        $caravans_info = model('CaravanInfos')->getCaravanInfo($caravan_id);
        
        $this->setRentDateLine($caravan_id, $caravans_info);
        $this->setShareDateline($caravan_id, $caravans_info);
    }
    /**
     * 房车分享时间段
     * @param [type] $caravan_id [description]
     */
    public function setShareDateline($caravan_id, $caravans_info)
    {
        $now_time       = date('Y-m-d');
        $dates = $this->where(['caravan_id' => $caravan_id, 'wishs' => 0, 'shares' => 1, 'orders' => 0])->where(['datetimes'=>['>=',$now_time]])->column('datetimes');
        if ($dates) {
            $date_lines = $this->combination($dates, false);
            foreach ($date_lines as $date_line) {
                model('CarCalendar')->create([
                    'sign' => self::CALENDAR_IS_SHARE,
                    'user_id' => $caravans_info->user_id, 
                    'camp_id' => $caravans_info->services,
                    'caravan_id' => $caravan_id, 
                    'bland_id' =>$caravans_info->branch_id,
                    'car_area' =>$caravans_info->area,
                    's' => $date_line['start'], 
                    'e' => $date_line['end']
                ], true);
            }
        }
    }
    /**
     * 房车出租时间段
     * @param [type] $caravan_id [description]
     */
    public function setRentDateLine($caravan_id, $caravans_info)
    { 
        $now_time       = date('Y-m-d');
        $dates = $this->where(['caravan_id' => $caravan_id, 'wishs' => 0, 'rents' => 1, 'orders' => 0])->where(['datetimes'=>['>=',$now_time]])->column('datetimes'); 
        if ($dates) {
            $date_lines = $this->combination($dates, false);
            foreach ($date_lines as $date_line) {
                model('CarCalendar')->create([
                    'sign' => self::CALENDAR_IS_RENT,
                    'user_id' => $caravans_info->user_id,
                    'camp_id' => $caravans_info->services,
                    'caravan_id' => $caravan_id, 
                    'bland_id' =>$caravans_info->branch_id,
                    'car_area' =>$caravans_info->area, 
                    's' => $date_line['start'], 
                    'e' => $date_line['end']
                ], true);
            }
        }
    }
    /**
     * 生成订单同步修改房车状态order=1订单生成=2订单完成
     * @param  [type] $caravan_id [description]
     * @param  [type] $user_id    [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @param  string $source     [description]
     * @return [type]             [description]
     */
    public function ordered($caravan_id,$start_date, $end_date = '',$source)
    {
        //订单生成
        //订单日期是否可行
        $result = $this->where('caravan_id', $caravan_id)->where('datetimes', 'between', [$start_date, $end_date])->column('orders');
        $a = ['1','2'];
        if (!in_array($a,$result)) {    
            $this->where('caravan_id', $caravan_id)->where('datetimes', 'between', [$start_date, $end_date])->update(['orders'=>1]);
           
        }
        $this->refreshCaravanStatuDateLine($caravan_id);
    }
    /**
     * 取消订单同步修改房车状态 未付款
     * @param  [type] $caravan_id [description]
     * @param  [type] $user_id    [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function delordered($caravan_id, $start_date, $end_date = '',$source)
    {
        //未付款取消订单
        $this->where('caravan_id', $caravan_id)->where('datetimes', 'between', [$start_date, $end_date])->update(['orders'=>0]);
        $this->refreshCaravanStatuDateLine($caravan_id);
    }
    public function sendSearchMsg()
    {
        SmsFactory::init('MailAliyun')->sendSearch('9714928@qq.com','有用户更新啦！');
    }
    /**
     * 校验用户可自由设置时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function checkUserCaravanDateSet($caravan_id, $start_date, $end_date = null)
    {
        $end_date = $end_date ? : $start_date;
        $query = $this->where('caravan_id', $caravan_id)->where('datetimes', 'between', [$start_date, $end_date]);
        return $query->where(function ($query) {
                $query->whereOr(['wishs' => 1, 'orders' => ['in', '1,2']]);
            })->count() ? false : true;
    }
    /**
     * 校验用户可wishi时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function checkUserCaravanDateSetWish($caravan_id, $start_date, $end_date = '')
    {
        $end_date = $end_date ? : $start_date;
        $query = $this->where('caravan_id', $caravan_id)->where('datetimes', 'between', [$start_date, $end_date]);
        return $query->where(function ($query) {
                $query->whereOr(['orders' => ['in', '1,2']]);
            })->count() ? false : true;
    }
    /**
     * 获取房车状态数组
     * @param  [type] $caravan_id [description]
     * @return [type]             [description]
     */
    public function getCaravanStatus($caravan_id, $sign = null)
    {
        $res = ['shares' => [], 'rents' => [], 'disables' => []];
        if ($caravanCalendars = $this->where('caravan_id', $caravan_id)->select()) { 
            foreach ($caravanCalendars as $calendar) {
                if ($calendar->shares == 1) {
                    $res['shares'][] = $calendar->datetimes;
                }
                if ($calendar->rents == 1) {
                    $res['rents'][] = $calendar->datetimes;
                }
                if ($calendar->wishs == 1 || $calendar->orders == 1 || $calendar->orders == 2) {
                    $res['disables'][] = $calendar->datetimes;
                }
                //$res['all'][] = $calendar->datetimes;
            }
            if ($sign && isset($res[$sign])) {
                return $res[$sign];
            }
            return $res;
        }
        return ;
    }
    public function test($region, $start_date, $end_date = '')
    {
        model('Camps')->where(['region' => $region]);
        empty($end_date) && $end_date = $start_date;
        $diff = intval(Carbon::createFromFormat('Y-n-j', $start_date)
        ->diffInDays(Carbon::createFromFormat('Y-n-j', $end_date)) * 0.1);

        $caravan_lists = $this->field('count(datetimes) as a, caravan_id')
                ->where(['datetimes' => ['between', [$start_date, $end_date]], 'shares' => 1, 'wishs' => 0, 'orders' => 0])
                ->group('caravan_id')
                ->having('a > '.$diff)
                ->order('a desc')
                ->limit(25)
                ->page(1)
                ->select();
        return $caravan_lists;
    }
}
